<script lang="ts">
	import { Tween } from 'svelte/motion';
	import { cubicOut } from 'svelte/easing';

	// 组件 props
	const {
		children,
		value = 0,
		max = 100,
		showText = true,
		color = 'var(--color-primary-700)',
		height = '8px',
		radius = '4px',
		duration = 300,
		easing = cubicOut,
		className = ''
	} = $props<{
		children?: any;
		value?: number;
		max?: number;
		showText?: boolean;
		color?: string;
		height?: string;
		radius?: string;
		duration?: number;
		easing?: (t: number) => number;
		className?: string;
	}>();

	// 安全值处理
	const safeValue = $state(Math.min(Math.max(value, 0), max));

	// 使用新的 Tween API - 直接将safeValue作为目标值
	const animatedValue = new Tween(safeValue, {
		duration,
		easing
	});

	// 计算显示百分比 - 通过$state.snapshot获取Tween的当前值
	const percentage = $derived(Math.round((animatedValue.current / max) * 100));

	// 进度条宽度
	const progressWidth = $derived(`${(animatedValue.current / max) * 100}%`);	
</script>

<div class="progress-wrapper {className}">
	<!-- 进度条容器 -->
	<div class="progress-bar-container" style="height: {height}">
		<!-- 进度条轨道 -->
		<div class="progress-track" style="border-radius: {radius}">
			<!-- 进度条填充 -->
			<div
				class="progress-fill"
				style="
                    background: {color};
                    border-radius: {radius};
                    width: {progressWidth};
                "
			></div>
		</div>
	</div>

	<!-- 进度文本 -->
	{#if showText}
		<div class="progress-text" style="color: {color}">
			{#if children}
				{@render children?.()}
			{:else}
				{percentage}%
			{/if}
		</div>
	{/if}
</div>

<style>
	.progress-wrapper {
		display: flex;
		flex-direction: column;
		gap: 8px;
		width: 100%;
	}

	.progress-bar-container {
		width: 100%;
		position: relative;
	}

	.progress-track {
		width: 100%;
		height: 100%;
		background: var(--color-info-200);
		overflow: hidden;
		position: relative;
	}

	.progress-fill {
		height: 100%;
		/* 移除CSS transition，因为动画由Tween处理 */
	}

	.progress-text {
		font-size: 14px;
		font-weight: 500;
		text-align: center;
		margin: 0;
		line-height: 1;
	}

	/* 光泽效果（可选） */
	.progress-fill::after {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: linear-gradient(
			90deg,
			transparent 0%,
			var(--color-primary-200) 50%,
			transparent 100%
		);
		animation: shine 2s infinite;
	}

	@keyframes shine {
		0% {
			transform: translateX(-100%);
		}
		100% {
			transform: translateX(100%);
		}
	}
</style>
